package com.wolfking.jeesite.controller;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.wolfking.jeesite.config.SsoConfig;
import com.wolfking.jeesite.entity.Area;
import com.wolfking.jeesite.entity.Dict;
import com.wolfking.jeesite.entity.Office;
import com.wolfking.jeesite.service.AreaService;
import com.wolfking.jeesite.service.DictService;
import com.wolfking.jeesite.service.OfficeService;
import com.wolfking.jeesite.sign.Sign;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 机构的controller
 * <p>
 *
 * @author wolfking@赵伟伟
 * @mail zww199009@163.com
 * @创作日期 2017年5月3日下午5:12:06
 * @版权 归wolfking所有
 */
@Slf4j
@Controller
@RequestMapping("/sys/office")
public class OfficeController {

    @Autowired
    private AreaService areaService;

    @Autowired
    private DictService dictService;

    @Autowired
    private OfficeService officeService;

    @Autowired
    private SsoConfig ssoConfig;

    /**
     * 机构的列表页面
     *
     * @param model
     * @return
     */
    @Sign(code = "sys:office:view")
    @RequestMapping(value = "/list", method = {RequestMethod.GET, RequestMethod.POST})
    public String list(Model model, Office office) {
        List<Office> list = Lists.newArrayList();
        List<Office> sourcelist;
        if (Objects.nonNull(office.getParentId()) && Objects.isNull(office.getId())
                || Objects.isNull(office.getParentId())
                || office.getParentId() == 0)
            sourcelist = officeService.list();
        else {
            sourcelist = officeService.getAllChild(office.getId());
            for (Office o : sourcelist)
                if (o.getId().equals(office.getId()))
                    o.setParentId(0);
        }
        sortList(list, sourcelist, 0, true);
        model.addAttribute("list", list);
        List<Area> areas = areaService.list();
        Map<String, String> areaMap = new HashMap<>();
        List<Dict> dicts = dictService.getByType("sys_office_type");
        Map<String, String> dictMap = new HashMap<>();
        for (Area area : areas)
            areaMap.put(area.getId() + "", area.getName());
        for (Dict dict : dicts)
            dictMap.put(dict.getValue(), dict.getLabel());
        model.addAttribute("areaMap", areaMap);
        model.addAttribute("dictMap", dictMap);
        return "sys/office/list";
    }

    /**
     * 机构的编辑页面
     *
     * @return
     */
    @Sign(code = "sys:office:view")
    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public String edit(Model model, Office office) {
        Area area = new Area();
        Office parent = new Office();
        if (Objects.nonNull(office.getId()))
            office = officeService.getById(office.getId());
        model.addAttribute("office", office);
        if (Objects.nonNull(office.getAreaId()))
            area = areaService.getById(office.getAreaId());
        model.addAttribute("area", area);
        List<Dict> types = dictService.getByType("sys_office_type");
        model.addAttribute("types", types);
        List<Dict> grades = dictService.getByType("sys_office_grade");
        model.addAttribute("grades", grades);
        if (Objects.nonNull(office.getParentId()) && office.getParentId() != 0)
            parent = officeService.getById(office.getParentId());
        model.addAttribute("parent", parent);
        return "sys/office/edit";
    }


    @Sign(code = "sys:office:view")
    @RequestMapping(value = "/copyEdit", method = RequestMethod.GET)
    public String copyEdit(Model model, Office office) {
        String view = edit(model, office);
        office = (Office) model.getAttribute("office");
        if (Objects.nonNull(office) && Objects.nonNull(office.getId())) {
            office.setName(office.getName() + "-2");
            if (Objects.nonNull(office.getSort())) {
                office.setSort(office.getSort() + 1);
            } else {
                office.setSort(0);
            }
            office.setId(null);
            office.setCreateTime(null);
            office.setUpdateTime(null);
            office.setVersion(0);
        }
        return view;
    }

    /**
     * 机构的保存或者修改
     *
     * @return
     */
    @Sign(code = "sys:office:edit")
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public String edits(Office office,RedirectAttributes redirectAttributes) {
        if (Objects.nonNull(office.getId())) {
            officeService.updateById(office);
            redirectAttributes.addFlashAttribute("message", "修改机构成功");
        } else {
            officeService.save(office);
            redirectAttributes.addFlashAttribute("message", "添加机构成功");
        }
        return ssoConfig.getRedirectWithPath("/sys/office/list");
    }

    /**
     * 删除区域
     *
     * @param id
     * @return
     */
    @Sign(code = "sys:office:edit")
    @RequestMapping(value = "/delete", method = RequestMethod.GET)
    public String delete(@RequestParam Integer id) {
        if (Objects.nonNull(id))
            officeService.deleteById(id);
        return ssoConfig.getRedirectWithPath("/sys/office/list") ;
    }

    @Sign
    @ResponseBody
    @RequestMapping(value = "/allTreeData", method = RequestMethod.GET)
    public List<Map<String, Object>> allTreeData() {
        List<Map<String, Object>> mapList = Lists.newArrayList();
        List<Office> list = officeService.list();
        for (int i = 0; i < list.size(); i++) {
            Office e = list.get(i);
            Map<String, Object> map = Maps.newHashMap();
            map.put("id", e.getId());
            map.put("pId", e.getParentId());
            map.put("pIds", e.getParentIds());
            map.put("name", e.getName());
            map.put("type", e.getType());
            mapList.add(map);
        }
        return mapList;
    }

    @Sign
    @ResponseBody
    @RequestMapping(value = "treeData")
    public List<Map<String, Object>> treeData(
            @RequestParam(required = false) Integer extId,
            @RequestParam(required = false) String type, @RequestParam(required = false) Long grade,
            @RequestParam(required = false) Boolean isAll, HttpServletResponse response) {
        List<Map<String, Object>> mapList = Lists.newArrayList();
        List<Office> list = officeService.list();
        for (int i = 0; i < list.size(); i++) {
            Office e = list.get(i);
            if (!e.getId().equals(extId) && "1".equals(e.getUseable())
                    && (StringUtils.isEmpty(type) || e.getType().equals(type))) {
                Map<String, Object> map = Maps.newHashMap();
                map.put("id", e.getId());
                map.put("pId", e.getParentId());
                map.put("pIds", e.getParentIds());
                map.put("name", e.getName());
                if ("3".equals(type)) {
                    map.put("isParent", true);
                }
                mapList.add(map);
            }
        }
        return mapList;
    }

    @Sign
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index() {
        return "sys/office/index";
    }

    private void sortList(List<Office> list, List<Office> sourcelist, Integer parentId, boolean cascade) {
        for (int i = 0; i < sourcelist.size(); i++) {
            Office e = sourcelist.get(i);
            if (parentId.equals(e.getParentId())) {
                list.add(e);
                if (cascade) {
                    // 判断是否还有子节点, 有则继续获取子节点
                    for (int j = 0; j < sourcelist.size(); j++) {
                        Office child = sourcelist.get(j);
                        if (e.getId().equals(child.getParentId())) {
                            sortList(list, sourcelist, e.getId(), true);
                            break;
                        }
                    }
                }
            }
        }
    }

}
